import os
import sys
import threading
import subprocess
import time

class SimpleMusicPlayer:
    def __init__(self):
        self.playing = False
        self.process = None
        self.current_track = None

    def play_music(self, file_path):
        """播放音乐文件"""
        if not os.path.exists(file_path):
            print(f"错误: 文件 '{file_path}' 不存在。")
            return

        self.playing = True
        self.current_track = file_path

        # 根据操作系统选择播放命令
        if os.name == 'nt':  # Windows
            self.process = subprocess.Popen(['start', file_path], shell=True)
        elif sys.platform == 'darwin':  # macOS
            self.process = subprocess.Popen(['afplay', file_path])
        else:  # Linux
            self.process = subprocess.Popen(['xdg-open', file_path])

        print(f"正在播放: {file_path}")

        # 等待播放结束
        while self.playing and self.process.poll() is None:
            time.sleep(0.5)

        self.playing = False
        self.process = None
        print("播放结束。")

    def stop_music(self):
        """停止当前播放的音乐"""
        if not self.playing:
            print("没有正在播放的音乐。")
            return

        try:
            if os.name == 'nt':  # Windows
                os.system('taskkill /f /im wmplayer.exe 2>nul')  # 关闭 Windows Media Player
            elif sys.platform == 'darwin':  # macOS
                os.system('pkill -f afplay 2>/dev/null')
            else:  # Linux
                os.system('pkill -f vlc 2>/dev/null')
                os.system('pkill -f xdg-open 2>/dev/null')

            self.playing = False
            print("音乐已停止。")
        except Exception as e:
            print(f"停止音乐时出错: {e}")

def main():
    player = SimpleMusicPlayer()

    while True:
        user_input = input("请输入音乐文件路径（或输入 'stop' 停止播放，'quit' 退出程序）: ").strip()

        if user_input.lower() == 'quit':
            if player.playing:
                player.stop_music()
            print("再见！")
            break
        elif user_input.lower() == 'stop':
            player.stop_music()
        else:
            if player.playing:
                print("正在播放其他音乐，请先停止当前播放。")
                continue

            # 异步播放音乐
            play_thread = threading.Thread(target=player.play_music, args=(user_input,))
            play_thread.daemon = True
            play_thread.start()

if __name__ == "__main__":
    main()
